﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class CustomDebugInformationRule : ILRule<CustomDebugInformationHandle>
    {
        [ILInfo]
        public EntityHandle Parent { get; }

        [ILInfo(true)]
        public Guid Kind { get; }

        [ILInfo]
        public byte[] Value { get; }

        public CustomDebugInformationRule(
            EntityHandle parent,
            Guid kind,
            byte[] value)
            : base()
        {
            Parent = parent;
            Kind = kind;
            Value = value;
        }

        public CustomDebugInformationRule(MetadataReader reader, CustomDebugInformationHandle customDebugInformationHandle)
            : base(reader)
        {
            CustomDebugInformation customDebugInformation = reader.GetCustomDebugInformation(customDebugInformationHandle);
            Parent = customDebugInformation.Parent;
            Kind = reader.GetGuid(customDebugInformation.Kind);
            Value = reader.GetBlobBytes(customDebugInformation.Value);
        }

        public override CustomDebugInformationHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddCustomDebugInformation(
                parent: Parent,
                kind: builder.GetOrAddGuid(Kind),
                value: Value == null ? default : builder.GetOrAddBlob(Value));
        }
    }
}